//
//  XMPPManager.m
//  myXMPP
//
//  Created by Radish on 16/3/19.
//  Copyright © 2016年 Radish. All rights reserved.
//

/*
    XMPP的登陆流程
    1、LoginToServer 初始化xmpp 设置服务器、端口 调用 connectWithTimeout 连接到xmpp服务器
    2、在xmpp服务器回调代理 xmppStreamDidConnect 里面验证密码 [self sendPassWordToServer] 。
    3、在服务器回调 xmppStreamDidAuthenticate，默认登陆是不在线的 发送在线消息给服务器 [self sendOnlineMessage] 。
 */

#import "XMPPManager.h"
#import "XMPPFramework.h"

@interface XMPPManager()<XMPPStreamDelegate>

//xmpp核心类
@property (nonatomic, strong) XMPPStream *xmppStream;

@end

@implementation XMPPManager

static XMPPManager *manager;

+ (XMPPManager *) share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}
#pragma mark login
//登陆xmpp
- (void) LoginToServer{
    //初始化xmppStream
    self.xmppStream = [[XMPPStream alloc]init];
    [self.xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    //设置jid属性 resource 代表用户的设备
    XMPPJID *myJid = [XMPPJID jidWithUser:@"radish" domain:@"radish.local" resource:@"iPhone6"];
    //设置Jid 服务器地址 端口号
    self.xmppStream.myJID = myJid;
    self.xmppStream.hostName = @"127.0.0.1";
    self.xmppStream.hostPort = 5222;
    //连接到主机
    NSError *error = nil;
    [self.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error];
}
//往xmpp发送密码
- (void)sendPassWordToServer{
    NSError *error = nil;
    [self.xmppStream authenticateWithPassword:@"123456" error:&error];
}
//往xmpp发送 告诉服务器我在线了
- (void)sendOnlineMessage{
    XMPPPresence *presence = [XMPPPresence presence];
    [self.xmppStream sendElement:presence];
}

#pragma mark register

- (void)RegisterAcount{
}

#pragma mark xmpp delagate
//连接上scoket服务器
-(void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket{
    NSLog(@"socket connet");
}
//根据传入的 jid 连接上xmpp服务器
-(void)xmppStreamDidConnect:(XMPPStream *)sender{
    NSLog(@">>>> did connect >>>>%s",__func__);
    [self sendPassWordToServer];
}
//连接xmpp服务器失败
-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
    NSLog(@">>> socket fail to connet >>> %@",error);
}
//密码验证错误
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{
    NSLog(@">>> 密码验证失败 >> ");
}
//密码验证成功
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    NSLog(@">>>>> 密码验证成功 >>>> %s",__func__);
    [self sendOnlineMessage];
}
@end
